package com.example.managemyself.ui.settings;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.managemyself.R;
import com.example.managemyself.data.repository.RepositoryFactory;
import com.example.managemyself.util.DatabaseSettingsManager;
import com.example.managemyself.util.MySQLConnectionHelper;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 数据库设置Fragment
 */
public class DatabaseSettingsFragment extends Fragment {

    private SwitchMaterial switchRemoteDatabase;
    private TextInputEditText editDbHost;
    private TextInputEditText editDbPort;
    private TextInputEditText editDbName;
    private TextInputEditText editDbUser;
    private TextInputEditText editDbPassword;
    private Button btnTestConnection;
    private Button btnSaveSettings;

    private DatabaseSettingsManager settingsManager;
    private ExecutorService executorService;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        settingsManager = DatabaseSettingsManager.getInstance();
        executorService = Executors.newSingleThreadExecutor();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_database_settings, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化视图
        switchRemoteDatabase = view.findViewById(R.id.switch_remote_database);
        editDbHost = view.findViewById(R.id.edit_db_host);
        editDbPort = view.findViewById(R.id.edit_db_port);
        editDbName = view.findViewById(R.id.edit_db_name);
        editDbUser = view.findViewById(R.id.edit_db_user);
        editDbPassword = view.findViewById(R.id.edit_db_password);
        btnTestConnection = view.findViewById(R.id.btn_test_connection);
        btnSaveSettings = view.findViewById(R.id.btn_save_settings);

        // 加载设置
        loadSettings();

        // 设置监听器
        switchRemoteDatabase.setOnCheckedChangeListener((buttonView, isChecked) -> {
            updateFieldsEnabledState(isChecked);
        });

        btnTestConnection.setOnClickListener(v -> {
            testConnection();
        });

        btnSaveSettings.setOnClickListener(v -> {
            saveSettings();
        });
    }

    /**
     * 加载设置
     */
    private void loadSettings() {
        if (getContext() == null) return;

        boolean useRemoteDb = settingsManager.isUseRemoteDatabase(getContext());
        String host = settingsManager.getDbHost(getContext());
        String port = settingsManager.getDbPort(getContext());
        String name = settingsManager.getDbName(getContext());
        String user = settingsManager.getDbUser(getContext());
        String password = settingsManager.getDbPassword(getContext());

        // 设置UI
        switchRemoteDatabase.setChecked(useRemoteDb);
        editDbHost.setText(host);
        editDbPort.setText(port);
        editDbName.setText(name);
        editDbUser.setText(user);
        editDbPassword.setText(password);

        // 更新字段启用状态
        updateFieldsEnabledState(useRemoteDb);
    }

    /**
     * 保存设置
     */
    private void saveSettings() {
        if (getContext() == null) return;

        boolean useRemoteDb = switchRemoteDatabase.isChecked();
        String host = editDbHost.getText() != null ? editDbHost.getText().toString() : "";
        String port = editDbPort.getText() != null ? editDbPort.getText().toString() : "3306";
        String name = editDbName.getText() != null ? editDbName.getText().toString() : "";
        String user = editDbUser.getText() != null ? editDbUser.getText().toString() : "";
        String password = editDbPassword.getText() != null ? editDbPassword.getText().toString() : "";

        // 验证输入
        if (useRemoteDb) {
            if (host.isEmpty() || name.isEmpty() || user.isEmpty()) {
                Toast.makeText(getContext(), "请填写所有必填字段", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 保存设置
        settingsManager.saveAllSettings(getContext(), useRemoteDb, host, port, name, user, password);
        
        // 重新初始化数据库连接
        MySQLConnectionHelper.getInstance().initialize(getContext());
        
        // 更新仓库设置
        RepositoryFactory.setUseRemoteRepository(getContext(), useRemoteDb);

        Toast.makeText(getContext(), "设置已保存", Toast.LENGTH_SHORT).show();
    }

    /**
     * 测试数据库连接
     */
    private void testConnection() {
        if (getContext() == null) return;

        String host = editDbHost.getText() != null ? editDbHost.getText().toString() : "";
        String port = editDbPort.getText() != null ? editDbPort.getText().toString() : "3306";
        String name = editDbName.getText() != null ? editDbName.getText().toString() : "";
        String user = editDbUser.getText() != null ? editDbUser.getText().toString() : "";
        String password = editDbPassword.getText() != null ? editDbPassword.getText().toString() : "";

        // 验证输入
        if (host.isEmpty() || name.isEmpty() || user.isEmpty()) {
            Toast.makeText(getContext(), "请填写所有必填字段", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示正在测试
        btnTestConnection.setEnabled(false);
        btnTestConnection.setText("正在测试连接...");

        // 在后台线程中测试连接
        executorService.execute(() -> {
            Connection connection = null;
            boolean success = false;
            String errorMessage = "";

            try {
                // 使用反射创建测试连接
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://" + host + ":" + port + "/" + name + "?useSSL=false";
                connection = java.sql.DriverManager.getConnection(url, user, password);
                success = true;
            } catch (ClassNotFoundException e) {
                errorMessage = "找不到MySQL JDBC驱动: " + e.getMessage();
            } catch (SQLException e) {
                errorMessage = "连接失败: " + e.getMessage();
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        // 忽略关闭错误
                    }
                }
            }

            // 在UI线程中更新结果
            final boolean finalSuccess = success;
            final String finalErrorMessage = errorMessage;
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    btnTestConnection.setEnabled(true);
                    btnTestConnection.setText("测试连接");
                    if (finalSuccess) {
                        Toast.makeText(getContext(), "连接成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), finalErrorMessage, Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
    }

    /**
     * 更新字段启用状态
     */
    private void updateFieldsEnabledState(boolean enabled) {
        editDbHost.setEnabled(enabled);
        editDbPort.setEnabled(enabled);
        editDbName.setEnabled(enabled);
        editDbUser.setEnabled(enabled);
        editDbPassword.setEnabled(enabled);
        btnTestConnection.setEnabled(enabled);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        executorService.shutdown();
    }
} 